package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Product;
import cn.wolfcode.trip.base.domain.ProductContent;
import cn.wolfcode.trip.base.mapper.ProductContentMapper;
import cn.wolfcode.trip.base.mapper.ProductMapper;
import cn.wolfcode.trip.base.query.ProductQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/** tiger
 * 商品
 */
@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductContentMapper contentMapper;

    /** tiger
     * 查询所以商品信息(分页)
     * @param qo
     * @return
     */
    public PageInfo<Product> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Product> list = productMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    /** tiger
     * 新增或编辑商品
     * @param product
     */
    public void saveOrUpdate(Product product) {
        if (product.getId() != null) {
            //获取商品详情的数据
            ProductContent content = product.getProductContent();
            content.setId(product.getId());
            content.setContent(product.getProductContent().getContent());
            //同时保存详情
            contentMapper.updateByPrimaryKey(content);
            productMapper.updateByPrimaryKey(product);
        }else{
            ProductContent content = product.getProductContent();
            //先保存商品,可以获取id
            productMapper.insert(product);
            //获取商品id,给商品详情
            content.setId(product.getId());
            contentMapper.insert(content);
        }
    }

    /** tiger
     * 删除操作
     * @param id
     */
    public void delete(Long id) {
        contentMapper.deleteByPrimaryKey(id);
        productMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Product selectProductById(Long productId) {
        return productMapper.selectByPrimaryKey(productId);
    }

    @Override
    public PageInfo<Product> query(ProductQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),0);
        List<Product> list=productMapper.selectForListApp(qo);
        return new PageInfo<>(list);
    }
}
